<template>
  <Dialog
    :title="formData.data.id ? '编辑' : '新增' + '推送消息'"
    :modal-outside="false"
    v-model="visible"
    :width="880"
    align-center
  >
    <el-form 
      ref="formRef" 
      :inline="true" 
      :model="formData.data" 
      :rules="formRules" 
      class="-mb-15px"
      label-width="auto"
    >
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="消息标题" prop="title">
            <el-input class="formInp" v-model="formData.data.title" clearable placeholder="请输入消息标题"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="消息类型" prop="senderType">
            <el-select class="formInp" v-model="formData.data.senderType" placeholder="请选择消息类型">
              <el-option v-for="item in msgLableList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" :class="formData.data.btnId ? 'mb-24': ''">
          <el-form-item label="消息用户清单" prop="btnId">
            <div class="flex-s mb-12">
              <el-button
                v-for="(item, index) in btnList"
                :key="item.id"
                :type="item.isCheck ? 'primary' : 'default'"
                @click="checkBtn(item, index)"
              >
                {{ item.name }}
              </el-button>
            </div>
            <el-select v-if="formData.data.btnId === 1" class="formInp" v-model="formData.data.senderUserType" placeholder="请选择用户类型">
              <el-option label="劳务员工" :value="1" />
              <el-option label="内部员工" :value="2" />
              <el-option label="全部员工" :value="3" />
            </el-select>
            <el-select 
              v-if="formData.data.btnId === 2"
              class="formInp" 
              v-model="formData.data.roleIdList" 
              placeholder="请选择角色用户" 
              multiple
              clearable
              filterable
            >
              <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-tree-select
              v-if="formData.data.btnId === 3"
              v-model="formData.data.deptIdList"
              :data="newTreeData"
              multiple
              :render-after-expand="false"
              show-checkbox
              filterable
              clearable
              placeholder="请选择所属部门"
              default-expand-all
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="消息内容" prop="content">
            <Editor v-model="formData.data.content" height="260px" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" :loading="loading" @click="submitForm">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup>
  import {ref,reactive,defineEmits} from "vue"
  import { formRules } from './formRules'
  import { getMsgPushDetail, addMsgPush, editMsgPush } from '@/api/viewsApi/msgPush'
  const visible = ref(false)
  const formData = reactive({
    data: {
      btnId: null,
      title: '',
      senderType: '', // 消息类型
      senderUserType: '', // 消息发送人类型
      roleIdList: [], // 角色用户
      deptIdList: [], // 部门用户
      content: '' // 消息内容
    }
  })
  const loading = ref(false) // 列表的加载中
  const msgLableList =  inject('msgLableList')
  const deptTree = inject('deptTree') // 树形结构
  const roleList = inject('roleList') // 角色列表
  const newTreeData = ref([])
  const formRef = ref(null)
  const getList = inject('getList',()=> {})
  const btnList = ref([
    {id: 1, name: '添加用户', isCheck: false},
    {id: 2, name: '按角色添加用户', isCheck: false},
    {id: 3, name: '按部门添加用户', isCheck: false},
  ])
  const message = useMessage() // 消息弹窗
  /** 查询详情信息 */
  const init = async (id) => {
    formData.data = {
      btnId: null,
      title: '',
      senderType: '', // 消息类型
      senderUserType: '', // 消息发送人类型
      roleIdList: [], // 角色用户
      deptIdList: [], // 部门用户
      content: '' // 消息内容
    }
    btnList.value.forEach(item => item.isCheck = false)
    newTreeData.value = setTreeData(deptTree.value)
    visible.value = true
    if(!id) return
    loading.value = true
    try {
      const data = await getMsgPushDetail(id)
      if(data.senderUserType){
        btnList.value[0].isCheck = true
        data.btnId = 1 
      }else{
        data.btnId = null
      }
      formData.data = data
    } finally {
      loading.value = false
    }
  }

  function setTreeData(tree) {
    return tree.map(node => {
      const newNode = {
        value: node.id,
        label: node.name,
        // 复制其他属性（如果有需要可以加上）
        ...node
      };
      delete newNode.id;
      delete newNode.name;
      if (node.children && node.children.length > 0) {
        newNode.children = setTreeData(node.children);
      }
      return newNode;
    });
  }

  const checkBtn = (item, index) => {
    const {id, isCheck} = item
    if(isCheck){
      btnList.value[index].isCheck = false
      formData.data.btnId = null
    }else{
      for(let item of btnList.value){
        item.isCheck = false
      }
      btnList.value[index].isCheck = true
      formData.data.btnId = id
    }
  }
  /** 提交表单 */
  const submitForm = async () => {
    const formEl = formRef.value
    if (!formEl) return

    await formEl.validate((valid, fields) => {
      if (valid) {
        const { 
          id,
          btnId,     
          title,
          senderType,
          senderUserType, // 消息发送人类型
          roleIdList, // 角色用户
          deptIdList, // 部门用户
          content, // 消息内容
        } = formData.data
        const parmsData = {
          id,
          title,
          senderType, // 消息类型
          content, // 消息内容
        }
        if(!btnId){
          message.error('请选择消息用户清单')
          return
        }
        if(btnId === 1 && !senderUserType){
          message.error('请选择消息发送人类型')
          return
        } 
        if(btnId === 2 && (!roleIdList || roleIdList.length === 0)){
          message.error('请选择角色用户')
          return
        } 
        if(btnId === 3 && (deptIdList || deptIdList.length === 0)){
          message.error('请选择部门用户')
          return
        }
        if(btnId === 1){
          parmsData.senderUserType = senderUserType
        } 
        if(btnId === 2){
          parmsData.roleIdList = roleIdList
        } 
        if(btnId === 3){
          parmsData.deptIdList = deptIdList
        }
    
        loading.value = true
        if (id) {
          editMsgPush(parmsData).then(res => {
            message.success('编辑成功')
            getList()
            visible.value = false
          }).finally(() => {
            loading.value = false
          })
        } else {
          addMsgPush(parmsData).then(res => {
            message.success('新增成功')
            getList()
            visible.value = false
          }).finally(() => {
            loading.value = false
          })
        }

      } else {
        for(let key in fields){
          ElMessage.error(fields[key][0].message)
        }
      }
    })
  }

  defineExpose({
    init
  })
</script>
<style lang="scss" scoped>
::v-deep .el-form-item{
  width: 100%;
}
.formInp{
  width: 100%;
}
::v-deep .el-select--default{
  width: 100% !important;
}
::v-deep .border-solid{
  width: 100%;
}
</style>
